package com.ddpt.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * mybatisPlus配置
 */
@Component
public class MybatisPlusConfig {

    @Value("${mybatis_fill.insert.enable:true}")
    private  Boolean MYBATIS_FILL_INSERT_ENABLE;

    @Value("${mybatis_fill.update.enable:true}")
    private  Boolean MYBATIS_FILL_UPDATE_ENABLE;

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    @Bean
    public MetaObjectHandler metaObjectHandler(){
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject meta) {
                if (MYBATIS_FILL_INSERT_ENABLE) {
                    this.fillStrategy(meta, "createTime", System.currentTimeMillis());
                    this.fillStrategy(meta, "updateTime", System.currentTimeMillis());
                    this.fillStrategy(meta, "deleted", 0);
                }
            }

            @Override
            public void updateFill(MetaObject meta) {
                if (MYBATIS_FILL_UPDATE_ENABLE) {
                    this.fillStrategy(meta, "updateTime", System.currentTimeMillis());
                }
            }

            @Override
            public MetaObjectHandler fillStrategy(MetaObject metaObject, String fieldName, Object fieldVal) {
                setFieldValByName(fieldName, fieldVal, metaObject);
                return this;
            }
        };
    }
}
